from django.db import models
import json
from .lib.fun import *

class Font(models.Model):
    class Meta:
        db_table = 'font'

    name = models.CharField(max_length=32)
    code = models.CharField(max_length=32)
    ttf = models.CharField(max_length=50, db_column='font_ttf')
    designer = models.CharField(max_length=50)
    license = models.CharField(max_length=20)
    website = models.CharField(max_length=200)
    commercialLicense = models.CharField(max_length=200, db_column='commercial_license')
    downloadUrl = models.CharField(max_length=500, db_column='download_url')
    characterMapUrl = models.CharField(max_length=500, db_column='character_map_url')

    seoTitle = models.CharField(max_length=500, db_column='seo_title', default='')
    seoKeywords = models.CharField(max_length=500, db_column='seo_keywords', default='')
    seoDescription = models.CharField(max_length=500, db_column='seo_description', default='')

    info = models.TextField()
    createTime = models.DateTimeField(db_column='create_time', auto_now_add=True)
    updateTime = models.DateTimeField(db_column='update_time', auto_now=True)

    licenseConf = {
        'demo': 'Demo',
        'free': 'Free',
        'donationware': 'Donationware',
        'free_for_personal_use': 'Free for Personal Use',
        'public_domain__gpl__ofl': 'Public domain, GPL, OFL',
        'shareware': 'Shareware',
    }

    def getSeoTitle(self, SEO):
        return self.seoTitle if self.seoTitle else (self.name+' Font - ' + SEO['title'])

    def getSeoDescription(self, SEO):
        return self.seoDescription if self.seoDescription else SEO['description']

    def getSeoKeywords(self, SEO):
        return self.seoKeywords if self.seoKeywords else (self.name+' Font,' + SEO['keywords'])

class Category(models.Model):
    class Meta:
        db_table = 'category'

    name = models.CharField(max_length=32)

class FontCategory(models.Model):
    class Meta:
        db_table = 'font_category'

    fontId = models.IntegerField(db_column='font_id')
    cateId = models.IntegerField(db_column='cate_id')


@cache(3600*12)
def GetDesigners():
    arr = set()
    for r in Font.objects.all().values('designer'):
        arr.add(r['designer'])

    return arr

@cache(3600*12)
def GetCates():
    arr = []
    for r in Category.objects.filter(id__in=FontCategory.objects.filter().values_list('cateId', flat=True)).order_by('name'):
        arr.append(r)

    return arr
 
def costTimeDownload(ip):
    rtype = 'download'
    rkey = ip
    num = getCache(rtype, rkey)
    if not num:
        num = 0

    setCache(rtype, rkey, num + 1, 3600*24)

    if num < 3:
        return 5
    if num < 8:
        return 5 + num - 3
    if num < 20:
        return 5 + num * 2 - 10
    if num > 60:
        return 600

    return 60
